use kdtree::KdTree;
use crate::exit;

#[derive(Debug, Clone, Copy)]
struct Point {
    x: f64,
    y: f64,

}

impl Point {
    fn new(x: f64, y: f64) -> Point {
        Point { x, y }
    }
    fn distance(&self, other: Point) -> f64 {
        const R: f64 = 6371.0; // 地球半径，单位为公里

        let lat1_rad = self.x.to_radians();
        let lon1_rad = self.y.to_radians();
        let lat2_rad = other.x.to_radians();
        let lon2_rad = other.y.to_radians();

        let dlat = lat2_rad - lat1_rad;
        let dlon = lon2_rad - lon1_rad;

        let a =
            (dlat / 2.0).sin().powi(2) + lat1_rad.cos() * lat2_rad.cos() * (dlon / 2.0).sin().powi(2);
        let c = 2.0 * a.sqrt().asin();

        R * c * 1000.0
    }
}

#[test]
fn main() {
    use crate::file::get_file_rows;
    let mut all_position = get_file_rows("building.txt", "请在当前目录添加楼宇文件:building.txt\n数据行格式:\n经度,纬度,楼宇ID\n经度,纬度,楼宇ID")
        .unwrap_or_else(|message| {
            println!("{}", message);
            exit()
        });
    // 生成50万个随机坐标
    let points: Vec<(Point, String)> = all_position.into_iter().map(|item| {
        let array: Vec<&str> = item.split(',').collect();
        (Point {
            x: array[0].parse::<f64>().unwrap(),
            y: array[1].parse::<f64>().unwrap(),
        }, array[2].to_string())
    }).collect();

    // 构建KD树
    let mut kdtree = KdTree::new(2);
    for (point, id) in points {
        kdtree.add([point.x, point.y], (point, id)).unwrap();
    }

    // 查询最近的坐标
    let query_point = Point { x: 106.619125, y: 29.711826 };
    if let Ok(res) = kdtree.nearest(&[query_point.x, query_point.y], 1, &|a, b| {
        Point::new(a[0], a[1]).distance(Point::new(b[0], b[1]))
    }) {
        let (distance, (point, id)) = res[0];
        // let nearest_point = points[index];
        println!("Nearest point:{:?},[{:?},{:?},{:?}]", distance,id, point.x, point.y);
    }
}
